<template>
    <Layout>
        <Row class="query-form">
            <Col span="24">
                <Button size="large" type="success"  v-if="currentRoleType == 1||currentRoleType == 2"  class="ivu-btn-add" icon="md-add" @click="insertRole">新增</Button>
                <Button size="large" :loading="menuButtonLoading" v-if="currentRoleType == 2" type="success"  class="ivu-btn-add" icon="md-add" @click="assignTwoLevelOrgMenu">分配在线端菜单范围</Button>
                <Button size="large" :loading="mobileMenuButtonLoading"  v-if="currentRoleType == 2" type="success"  class="ivu-btn-add" icon="md-add" @click="assignTwoLevelOrgMobileMenu">分配移动端菜单范围</Button>
            </Col>
        </Row>
        <Table ref='table' :loading="buttonLoading" stripe border no-data-text="没有查询到相关数据!" :height="tableHeight" :columns="columns3" :data="data1" size="small"></Table>
        <Page :total="pagedata.total"  @on-change="pageChange" @on-page-size-change="pageSizeChange" :current="pagedata.fromPage" :page-size="pagedata.pageSize"
                show-total show-sizer show-elevator>
        </Page>
        <Modal v-model="modal" title="分配电脑端功能" :styles="{height:'500px'}" class-name='limit-height-dialog'>
            <Tree ref="menuTree" :data="menuTree"  show-checkbox multiple ></Tree>
            <div slot="footer">
                <Button class='ivu-btn-save' :loading="buttonLoading" @click="saveMenus()" >确定</Button>
                <Button type="text"  class='ivu-btn-cancel'  @click="cancelMenu" >取消</Button>
            </div>
        </Modal>
        <Modal v-model="mobileModal" title="分配移动端功能" :styles="{height:'500px'}" class-name='limit-height-dialog'>
            <Tree ref="mobileMenuTree" :data="mobileMenuTree"  show-checkbox multiple></Tree>
            <div slot="footer">
                <Button class='ivu-btn-save' :loading="buttonLoading"  @click="saveMobileMenus()" >确定</Button>
                <Button type="text"  class='ivu-btn-cancel'  @click="cancel" >取消</Button>
            </div>
        </Modal>
        <Modal v-model="modal2" title="分配人员">
            <Tree ref="tree2" :data="paramsdatacopy"  :load-data="loadData" show-checkbox></Tree>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="makeSure2()" >确定</Button>
                <Button type="text"  class='ivu-btn-cancel'  @click="cancel2" >取消</Button>
            </div>
        </Modal>
        <Modal v-model="modal3" :styles="{top: '20px'}"  :title="RoleModalTitle">
            <Form :model="formItem" :label-width="140" >
                <FormItem label="角色名称：">
                    <Input v-model="formItem.name"></Input>
                </FormItem>
                <FormItem label="角色级别：" prop="roleType">
                    <Select v-model="formItem.roleType">
                        <Option v-if="currentRoleType<=1" value="1">集团公司级</Option>
                        <Option v-if="currentRoleType<=2" value="2">二级集团级</Option>
                        <Option v-if="currentRoleType<=3" value="3">企业级</Option>
                    </Select>
                </FormItem>
                <FormItem v-if="formItem.roleType == 2" label="所属集团：" prop="twoLevelCompany">
                    <Select v-model="formItem.orgId" placeholder="请选择二级集团">
                        <Option v-for="item in twoLevelOrgs" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="saveRole()" >确定</Button>
                <Button type="text"  class='ivu-btn-cancel'  @click="cancel3" >取消</Button>
            </div>
        </Modal>
        <Modal :transfer=true title="已分配人员" footer-hide v-model="userInRoleListModal"  :width=1000>
            <UserInRoleList  ref="userInRole" :userInRoleLoading="userInRoleLoading" :listData="listData" :companyName="companyName" :roleId="roleId" :totalNum="totalNum">
            </UserInRoleList>
        </Modal>
    </Layout>
</template>

<script>

import {Api} from '../../../api/index.js';
import {sessionStorage} from '../../../common/cacheUtils.js';
import UserInRoleList from './userInRoleList.vue';
import cascaderDom from '../../../components/cascader-dom'

export default {
        components: {
            UserInRoleList,cascaderDom
        },
        data() {
            return {
                twoLevelOrgs:[],
                currentLoginId: '',
                currentRoleType:'',
                totalNum : 0,
                roleId : '',
                companyId: '',
                companyName:'',
                userInRoleLoading:false,
                userInRoleListModal: false,
                listData : [],
                tableHeight:450,
                RoleModalTitle:"新增",
                currentRoleId:"",
                mobileMenu:false,
                selectNode: {}, //节点信息
                selectNodeInfo:{},
                selectRoot:{},
                menuTree:[{
                    menuId   : '100',
                    loading: true,
                    menuName : '菜单',
                    title: '菜单',
                    expand: true,
                    children: []
                }],
                mobileMenuTree:[{
                    menuId   : '100',
                    loading: true,
                    menuName : '菜单',
                    title: '菜单',
                    expand: true,
                    children: []
                }],
                modal:false,
                mobileModal:false,
                modal2:false,
                modal3:false,
                paramsdatacopy:[
                    {
                        title:'人员',
                        loading: true,
                        expand: true,
                        children: []
                    }
                ],
                formItem: {
                    name: "",
                    id:""
                },
                pagedata: {
                    total: 0, //总条数
                    fromPage: 1,//从n条开始
                    pageSize: 10//每页多少条
                },
                buttonLoading:false,
                menuButtonLoading:false,
                mobileMenuButtonLoading:false,
                tage: false,
                twoLevelRoleId:"",
                columns3: [{
                    title: '序号',
                    // type: 'index',
                    width: 70,
                    align: 'center',
                    render: (h, params) => {
                        return h('span', params.index + (this.pagedata.fromPage - 1) * this.pagedata.pageSize + 1);
                    }
                },
                    {
                        title: '角色名称',
                        width: 250,
                        align: "center",
                        key: 'name'
                    },
                    {
                        title: '角色级别',
                        width: 250,
                        align: "center",
                        render: (h, params) => {
                            return h('span', params.row.roleType === '1'? '集团公司级' :params.row.roleType === '2' ? '二级集团级':'公司级' );
                        }
                    },
                    {
                        title: '分配电脑端功能',
                        align: "center",
                        key: 'menu',
                        expand:true,
                        render:(h,params)=>{
                            return h('div',[
                                 h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (sessionStorage('userId').getObject('userId').loginId  != 'superadmin'  && params.row.createUserId != sessionStorage('userId').getObject('userId').userId ) ? '#d0d0d0':'red',
                                        pointerEvents:  (sessionStorage('userId').getObject('userId').loginId  != 'superadmin'  &&  params.row.createUserId != sessionStorage('userId').getObject('userId').userId) ? 'none':''
                                    },
                                    on:{
                                        click:() => {
                                            this.currentRoleId = this.data1[params.index].id;
                                            this.mobileMenu = false;
                                            this.getMenusByParentId('100');
                                            this.modal = true;
                                        }
                                    }
                                },"维护")
                            ])
                        }
                    },
                    {
                        title: '分配移动端功能',
                        align: "center",
                        key: 'menu',
                        expand:true,
                        render:(h,params)=>{
                            return h('div',[
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (sessionStorage('userId').getObject('userId').loginId  != 'superadmin' && params.row.createUserId != sessionStorage('userId').getObject('userId').userId) ? '#d0d0d0':'red',
                                        pointerEvents:  (sessionStorage('userId').getObject('userId').loginId  != 'superadmin' && params.row.createUserId != sessionStorage('userId').getObject('userId').userId) ? 'none':''
                                    },
                                    on:{
                                        click:() => {
                                            this.currentRoleId = this.data1[params.index].id;
                                            this.mobileMenu = true;
                                            this.getMenusByParentId('100');
                                            this.mobileModal = true;
                                        }
                                    }
                                },"维护")
                            ])
                        }
                    },
                    {
                        title: '分配人员',
                        key: 'role',
                        align: "center",
                        render:(h,params)=>{
                            return h('div',[
                              h('A', {
                                props: {
                                  type: 'primary',
                                  size: 'small'
                                },
                                style: {
                                  fontSize: '14px',
                                  color: 'red'
                                },
                                on:{
                                  click:() => {
                                    this.currentRoleId = this.data1[params.index].id;
                                    this.roleId = this.data1[params.index].id;
                                    this.userInRoleListModal = true;
                                    this.$refs.userInRole.resetPage();
                                    this.queryUsers(this.roleId);
                                  }
                                }
                              },"维护")
                            ])

                        }
                    },
                    {
                        title: '操作',
                        align: "center",
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (sessionStorage('userId').getObject('userId').loginId  != 'superadmin' && params.row.createUserId != sessionStorage('userId').getObject('userId').userId ) ? '#d0d0d0':'',
                                        pointerEvents:  (sessionStorage('userId').getObject('userId').loginId  != 'superadmin' && params.row.createUserId != sessionStorage('userId').getObject('userId').userId ) ? 'none':''
                                    },
                                    on: {
                                       click: () => {
                                            this.modify(params.index)
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: (sessionStorage('userId').getObject('userId').loginId  != 'superadmin' && params.row.createUserId != sessionStorage('userId').getObject('userId').userId ) ? '#d0d0d0':'red',
                                        pointerEvents:  (sessionStorage('userId').getObject('userId').loginId  != 'superadmin' && params.row.createUserId != sessionStorage('userId').getObject('userId').userId ) ? 'none':''
                                    },
                                    on: {
                                        click: () => {
                                            this.$Modal.confirm({
                                                title: '提示信息',
                                                content: '<p>删除该角色及其配置</p>',
                                                okText:'确认',
                                                cancelText:'取消',
                                                onOk: () => {
                                                    this.remove(params.index)
                                                }});
                                        }
                                    }
                                }, '删除')
                        ]);
                    }
                }
                ],
                data1: [{
                    name:"管理员",
                    id:1
                }
                ]
            }
        },
        mounted: function() {
            this.currentLoginId = sessionStorage('userId').getObject('userId').loginId;
            this.companyId = sessionStorage('userId').getObject('userId').companyId;
            this.companyName = sessionStorage('userId').getObject('userId').companyName;
            this.tableHeight = window.innerHeight - this.$refs.table.$el.parentNode.offsetTop-10 - 180;
            this.query()
            this.queryTwoOrgInfo();
        },
        methods: {
            queryTwoOrgInfo() {
                this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                    this.twoLevelOrgs = res.data.data;
                }).catch(e => {
                })
            },
            async queryTwoLevelRole(){
                await this.$http.get(Api.queryRoleByTwoLevel + "/" + sessionStorage('userId').getObject('userId').companyId).then(async res => {
                    if(res.data.status == "success") {
                        this.twoLevelRoleId = res.data.roleId;
                        if(this.twoLevelRoleId == undefined){
                              await this.$http.get(Api.saveRoleByTwoLevel + "/" + sessionStorage('userId').getObject('userId').companyId).then(res1 => {
                                if(res1.data.status == "success") {
                                    this.twoLevelRoleId = res1.data.roleId;
                                }
                            });
                        }
                    }
                }).catch(e => {
                })
            },
            async saveTwoLevelRole(){
                await this.$http.get(Api.saveRoleByTwoLevel + "/" + sessionStorage('userId').getObject('userId').companyId
                    + "?createUserId=" + sessionStorage('userId').getObject('userId').userId).then(res1 => {
                    if(res1.data.status == "success") {
                        this.twoLevelRoleId = res1.data.roleId;
                    }
                }).catch(e => {
                })
            },
            queryUsers(roleId){
                this.userInRoleLoading = true;
                let  data = {};
                data.fromPage = 1;
                data.pageSize = 10;
                data.roleId = roleId;
                data.companyName = this.companyName;
                data.userName = '';
                this.$http.get(Api.queryUserInRole, {params : data}).then(res => {
                    res.data.data.map(i=>{
                        if(i.orgInfo != null) {
                            i.orgName = i.orgInfo.orgName;
                        }
                    });
                    this.listData = res.data.data;
                    this.roleId = roleId;
                    this.totalNum = res.data.total;
                    this.userInRoleLoading = false;
                }).catch(e => {
                    this.userInRoleLoading = false;
                    //this.$Message.error('请求失败');
                })
            },
            pageChange(data){
                this.pagedata.fromPage = data;
                this.query();
            },
            pageSizeChange(size){
                this.pagedata.pageSize = size;
                this.query();
            },
            getMenusByParentId(parentMenuId){
                let url = "";
                if(this.mobileMenu == false){
                    this.menuTree=[
                        { menuId   : '100',
                            loading: true,
                            menuName : '菜单',
                            title: '菜单',
                            expand: true,
                            children: []}
                    ],
                    this.menuTree[0].children =[]
                    url = Api.queryRoleMenu + "/" + this.currentRoleId;
                    this.$http.get(url,{params:{parentMenuId : parentMenuId,orgId:sessionStorage('userId').getObject('userId').companyId}}).then(res => {
                        res.data.data.map(i=>{
                            if (i.children!=null){
                                i.checked=false
                                i.children.map(ii=>{
                                    if (ii.children!=null){
                                        ii.checked=false
                                        ii.children.map(iii=>{
                                            if (iii.children!=null){
                                                iii.checked=false
                                                iii.children.map(iiii=>{
                                                    if (iiii.children!=null){
                                                        iiii.checked=false
                                                        iiii.children.map(iiiii=>{
                                                            iiiii.checked=false
                                                            if (iiiii.funcs!=null){
                                                                iiiii.children = [];
                                                                iiiii.funcs.map(func=>{
                                                                    func.title = func.funcName;
                                                                    iiiii.children.push(func);
                                                                })
                                                            }
                                                        })
                                                    }
                                                })
                                            }
                                        })
                                    }
                                })
                            }
                        });
                    this.menuTree[0].children = res.data.data;
                    this.menuTree[0].loading = false;
                    }).catch(e => {
                    this.$Message.error('请求失败');
                    })
                }
                else{
                    this.mobileMenuTree = [{
                        menuId   : '100',
                        loading: true,
                        menuName : '菜单',
                        title: '菜单',
                        expand: true,
                        children: []
                    }]
                    url = Api.queryRoleMobileMenu + "/" + this.currentRoleId;
                    this.$http.get(url,{params:{parentMenuId : parentMenuId,orgId:sessionStorage('userId').getObject('userId').companyId}}).then(res => {
                        res.data.data.map(i=>{
                            if (i.children!=null){
                                    i.checked=false
                                    i.children.map(ii=>{
                                        if (ii.children!=null){
                                            ii.checked=false
                                            ii.children.map(iii=>{
                                                if (iii.children!=null){
                                                    iii.checked=false
                                                    iii.children.map(iiii=>{
                                                        if (iiii.children!=null){
                                                            iiii.checked=false
                                                            iiii.children.map(iiiii=>{
                                                                iiiii.checked=false
                                                            })
                                                        }
                                                    })
                                                }
                                            })
                                        }
                                    })
                                }
                            });
                        this.mobileMenuTree[0].children = res.data.data;
                        this.mobileMenuTree[0].loading = false;    
                    }).catch(e => {
                        this.$Message.error('请求失败');
                    })
                }
            },
            saveMenus(){
                this.buttonLoading = true;
                var menuData = "";
                var funcData = "";
                this.$refs.menuTree.getCheckedAndIndeterminateNodes().forEach(item=>{
                    if(item.menuId){
                        menuData = menuData  + item.menuId + ","
                    }else if(item.funcId){
                        funcData = funcData  + item.funcId + ","
                    }
                });
                menuData = menuData.substring(0, menuData.length - 1);
                funcData = funcData.substring(0, funcData.length - 1);
                let url = Api.updateRoleMenu + "/"+this.currentRoleId;
                this.$http.get(url, {params:{ menus : menuData,funcs : funcData }}).then(
                    res =>{
                        this.buttonLoading = false;
                        this.modal = false;
                        this.query();
                        this.$Message.success('保存成功');
                    }
                ).catch(
                    res=>{
                        this.buttonLoading = false;
                        this.$Message.error('请求失败');
                    }
                )
            },
            saveMobileMenus(){
                this.buttonLoading = true;
                var data = "";
                this.$refs.mobileMenuTree.getCheckedAndIndeterminateNodes().forEach(item=>{
                    data = data  + item.menuId + ","
                });
                data = data.substring(0, data.length - 1);

                this.$http.get(Api.updateRoleMobileMenu + "/"+this.currentRoleId, {params:{ menus : data }}).then(
                    res =>{
                        this.buttonLoading = false;
                        this.mobileModal = false;
                        this.query();
                        this.$Message.success('保存成功');
                    }
                ).catch(
                    res=>{
                        this.buttonLoading = false;
                        this.$Message.error('请求失败');
                    }
                )
            },
            cancel(){
                this.mobileModal = false;
                this.menuTree=[{
                menuId   : '100',
                menuName : '菜单',
                title: '菜单',
                expand: true,
                children: []
            }]},
            cancelMenu(){
                this.modal = false;
                this.menuTree=[{
                menuId   : '100',
                menuName : '菜单',
                title: '菜单',
                expand: true,
                children: []
            }]},
            makeSure2(){
                var data = "";
                this.$refs.tree2.getCheckedAndIndeterminateNodes().forEach(item=>{
                    if(item.type=="user")
                        data = data  + item.userId + ","
                })
                var menusData={}

                menusData.usersId = data
                this.$http.post(Api.baseUrl + "/role/users/"+this.currentRoleId,menusData).then(
                    res =>{
                        this.paramsdatacopy = [{
                            title:'人员',
                            loading: true,
                            expand: true,
                            children: []
                        }];
                    }
                ).catch(
                    res=>{
                        this.$Message.error('请求失败');
                    }
                )
                this.modal2 = false;
            },
            cancel2(){
                this.modal2 = false;
                this.paramsdatacopy=[{title:'人员',loading:false,children:[]}]
            },
            async assignTwoLevelOrgMenu(){
                this.menuButtonLoading = true;
                if(this.twoLevelRoleId == "" && sessionStorage('userId').getObject('userId').companyOrgLevel == '0200100005000000001')
                    await this.queryTwoLevelRole();
                if(this.twoLevelRoleId == undefined)
                    await this.saveTwoLevelRole();
                this.menuButtonLoading = false;
                this.currentRoleId = this.twoLevelRoleId;
                this.mobileMenu = false;
                this.getMenusByParentId('100');
                this.modal = true;
            },
            async assignTwoLevelOrgMobileMenu(){
                this.mobileMenuButtonLoading = true;
                if(this.twoLevelRoleId == "" && sessionStorage('userId').getObject('userId').companyOrgLevel == '0200100005000000001')
                    await this.queryTwoLevelRole();
                if(this.twoLevelRoleId == undefined)
                    await this.saveTwoLevelRole();
                this.mobileMenuButtonLoading = false;
                this.currentRoleId = this.twoLevelRoleId;
                this.mobileMenu = true;
                this.getMenusByParentId('100');
                this.mobileModal = true;
            },
            query(){
                this.buttonLoading=true
                let data = {}
                data.fromPage = this.pagedata.fromPage;
                data.pageSize = this.pagedata.pageSize;
                if(sessionStorage('userId').getObject('userId').loginId == this.Common.admin || sessionStorage('userId').getObject('userId').companyOrgLevel == '0200100005000000000'){
                    data.roleType = '1';
                    this.currentRoleType = 1;
                }
                else if(sessionStorage('userId').getObject('userId').companyOrgLevel == '0200100005000000001'){
                    data.roleType = '2';
                    this.currentRoleType = 2;
                }
                else {
                    data.roleType = '3';
                    this.currentRoleType = 3;
                }
                data.orgId = sessionStorage('userId').getObject('userId').companyId
                this.$http.get(Api.queryRole,{params:data}).then(
                    res =>{
                        this.pagedata.total=res.data.total;
                        this.data1 = res.data.data;
                        this.buttonLoading=false
                    }
                ).catch(
                    res=>{
                        this.$Message.error('请求失败');
                    }
                )
            },
            reset(){},
            getData(){
                this.query();
            },
            modify(index){
                this.RoleModalTitle="修改角色";
                this.modal3=true;
                this.formItem.name = this.data1[index].name;
                this.formItem.id = this.data1[index].id;
                this.formItem.roleType = this.data1[index].roleType;
                this.formItem.orgId = this.data1[index].orgId;
            },
            cancel3(){this.modal3 = false},
            saveRole(){
                if(this.formItem.id == ""){
                    this.formItem.orgId = sessionStorage('userId').getObject('userId').companyId;
                    this.formItem.createUserId = sessionStorage('userId').getObject('userId').userId;
                    this.$http.post(Api.addRole,this.formItem).then(res=>{
                        this.modal3 = false;
                        this.query();
                        this.$Message.success('保存成功');
                    }).catch(res=>{
                        this.$Message.error('请求失败');
                    })
                }else{
                    this.$http.post(Api.updateRole,this.formItem).then(res=>{
                        this.modal3 = false;
                        this.query();
                        this.$Message.success('修改成功');
                    }).catch(res=>{
                        this.$Message.error('请求失败');
                    })
                }
            },
            remove(index){
                this.$http.get(Api.deleteRole + "/" + this.data1[index].id, {params:{} }).then((res) => {
                    this.query();
                    this.$Message.success('删除成功');
                }).catch(res=>{
                    this.$Message.error('请求失败');
                })
            },
            loadData () {
                this.$http.get(Api.baseUrl + "/role/users/"+this.currentRoleId,{params:{}}).then((res) => {

                    this.paramsdatacopy[0].loading = false
                    this.paramsdatacopy[0].children.push(res.data.data);
                    //				this.paramsdatacopy.push(res.data.data);

                }).catch(res => {
                    this.$Message.error('请求失败');
                })
            },
            insertRole(){
                this.RoleModalTitle="新增角色";
                this.formItem.id="";
                this.formItem.name="";
                this.formItem.orgType="";
                this.formItem.orgId="";
                this.modal3=true;
            }
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';

</style>
